from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.conf import settings

from system.models import Router, OperationDetail
from utils.common.request_handle import RouteUnBind


class UnBindRouteView:
    """解绑路由器"""

    def unbind(self, request, route_obj, *args, **kwargs):
        try:
            hmac = route_obj.hmac_addr
            mac_addr = route_obj.mac_addr

            # 判断是否绑定服务器
            if not route_obj.server_addr:
                result = {'code': 10011, 'msg': '未绑定不能解绑'}
            else:
                # 发送请求，解绑
                rub = RouteUnBind()
                result = rub.route_unbind(mac_addr, hmac)
                if result.get('code') == 0:
                    # 更新数据库
                    updata_params = {
                        'server_addr': "",
                        'tunnel': None,
                        'bind_time': None,
                    }
                    Router.objects.filter(mac_addr=mac_addr).update(**updata_params)
                    OperationDetail.objects.create(operation_type=1, result="{} 解绑成功".format(mac_addr),
                                                   user=request.user)  # 记录操作记录
        except Exception as e:
            print(e)
            result = {'code': 10011, 'msg': '解绑失败'}

        return result


def check_role(func):
    """
    检查当前登陆用户是否是 "后台管理" 角色，若是，则跳转到首页，否则跳转到路由器管理页面
    :param func:
    :return:
    """
    def inner(request, *args, **kwargs):
        role_list = request.user.roles.all()
        if len(role_list) > 0:
            if role_list[0].name in settings.USER_ROLE_NAME:
                return redirect('rbac:system')  # 跳转到后台管理，显示侧边栏

        return func(request)

    return inner
